package com.open.core.handler;

import com.alibaba.fastjson2.JSON;

import com.open.core.entity.ChatMessage;
import com.open.core.common.Result;
import com.open.core.entity.type.MessageType;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

import static com.open.core.NettyServer.GROUP;
import static com.open.core.NettyServer.USERS;

public class ChatHandler {
    public static void excute(ChannelHandlerContext ctx, TextWebSocketFrame frame){
        try {
            ChatMessage chat = JSON.parseObject(frame.text(), ChatMessage.class);
            switch (MessageType.match(chat.getType())){
                case PRIVATE:{
                    if(StringUtil.isNullOrEmpty(chat.getTarget())){
                        ctx.channel().writeAndFlush(Result.fail("发送失败，消息发送前请指定接收对象"));
                        return;
                    }
                    Channel channel = USERS.get(chat.getTarget());
                    if (null == channel || !channel.isActive()){
                        ctx.channel().writeAndFlush(Result.fail("消息发送失败，对方" +chat.getTarget() +"不在线"));
                        return;
                    }else{
                        channel.writeAndFlush(Result.success("receive",chat.getContent(),chat.getNickname()));
                    }
                    break;
                }
                case GROUP:{
                    //todo 修改
                    GROUP.writeAndFlush(Result.success("群消息 发送者（" + chat.getNickname() +"）" , chat.getContent()));
                    break;
                }
                default:ctx.channel().writeAndFlush(Result.fail("ChatMessage 消息类型错误"));
            }
        }catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail("发送消息格式错误，请确认后在试"));
        }
    }
}
